/*
 * @lc app=leetcode.cn id=526 lang=typescript
 *
 * [526] 优美的排列
 */

// @lc code=start
function countArrangement(n: number): number {
  const visited = new Array(n + 1).fill(0);
  let ans = 0;
  const backtrack = (idx: number) => {
    if (idx === n + 1) {
      ans++;
      return;
    }

    for (let i = 1; i <= n; i++) {
      if (visited[i]) continue;
      // 满足条件的，继续找下一个元素
      if (i % idx === 0 || idx % i === 0) {
        visited[i] = 1;
        backtrack(idx + 1);
        visited[i] = 0;
      }
    }
  };

  backtrack(1);

  return ans;
}
// @lc code=end
